package com.tingyuge.thinking.spring.dependency.injection;

import com.tingyuge.thinking.spring.dependency.injection.annotation.UserGroup;
import com.tingyuge.thinking.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

import java.util.Collection;
import java.util.Set;

/**{@link org.springframework.beans.factory.ObjectFactory} 实现延迟注入
 * @author xiaodao
 * @version 1.0
 * @date 2021/6/29
 */
public class LazyDependencyInjectionDemo {


    @Autowired
    private User user;

    @Autowired
    private ObjectProvider<User> userObjectProvider;
    @Autowired
    private ObjectFactory<Set<User>> setObjectFactory;

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        //注册 configuration class（配置类）
        applicationContext.register(LazyDependencyInjectionDemo.class);

        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(applicationContext);
        String xmlClassPath = "classpath:/META-INF/dependency-lookup-context.xml";
        beanDefinitionReader.loadBeanDefinitions(xmlClassPath);
        //通过BeanDefinition 注册API 方式
        //启动应用上下文
        applicationContext.refresh();
        LazyDependencyInjectionDemo demo = applicationContext.getBean(LazyDependencyInjectionDemo.class);
        //输出primary User
        System.out.println("demo.user:"+ demo.user);
        //objectProvider 继承了 objectFactory
        System.out.println("demo.user:"+ demo.userObjectProvider.getObject());
        System.out.println("demo.user:"+ demo.setObjectFactory.getObject());
        System.out.println();
        for (User user : demo.userObjectProvider) {
            System.out.println(user);

        }

        //显示关闭应用上下文
        applicationContext.close();
    }
}
